# -*- coding: utf-8 -*-

#    Copyright (C) 2014 by Promotux
#                       di Francesco Meloni snc - http://www.promotux.it/

#    Author: Francesco Meloni  <francesco@promotux.it>

#    This file is part of OdCollect.

#    OdCollect is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 2 of the License, or
#    (at your option) any later version.

#    OdCollect is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.

#    You should have received a copy of the GNU General Public License
#    along with OdCollect.  If not, see <http://www.gnu.org/licenses/>.

import base64
import datetime
from web_lib.page import Page
from web_lib.webutils import Response, expose , json, leggiInSessione
from dao.TipoGeo import TipoGeo
from dao.Licenza import Licenza
from dao.Tag import Tag
from lib.utils import mN, prep2json
from random import randint as rint
from sqlalchemy import func
import Environment

@expose('/pg/ac_Categoria/<action>')
@expose('/pg/ac_Categoria/')
@expose('/pg/ac_Categoria')
def anagraficaCategoria(req, action=None):
    """
  id serial NOT NULL,
  denominazione_breve character varying(10) NOT NULL,
  denominazione character varying(100) NOT NULL,
  id_tipo integer NOT NULL,
    """
    from dao.TipoCategoria import TipoCategoria
    from dao.Categoria import Categoria
    def __show__(req, action=None):
        pageData = {'file': "/pg/ac_Categoria"}
        return Page(req).render(pageData)

    def __list__(req, action=None):
        sorting = req.args.get("jtSorting")
        offset = req.args.get("jtStartIndex")
        batchSize = req.args.get("jtPageSize")
        fk_denominazione = req.form.get("fk_denominazione")
        daos = Categoria().select(denominazione=fk_denominazione,
                            batchSize=batchSize,
                            offset=offset,
                            orderBy=sorting)
        count = Categoria().count(denominazione=fk_denominazione,
                                    batchSize=None)
        item = {
            "Result":"OK",
            "TotalRecordCount": count,
            "Records": prep2json(daos)
            }
        jasoned = json.dumps(item, ensure_ascii=False, encoding='utf8')
        return Response(jasoned)

    def __edit__(req, action=None):
        from dao.Tag import Tag
        from dao.CategoriaTag import CategoriaTag
        id = req.form.get("id")
        if id:
            d = Categoria().getRecord(id=int(id))
        else:
            d = Categoria()

        pageData = {'file': "pg/addedit/ae_categoria",
                    "dao": d,
                    "tipigeo":TipoGeo().select(batchSize=None),
                    "tipicategorie": TipoCategoria().select(batchSize=None),
                    "licenze": Licenza().select(batchSize=None),
                    "catetags":','.join([x.tag_name for x in CategoriaTag().select(id_categoria=d.id, batchSize=None)]),
                    "tags":Tag().select(batchSize=None)
                    }
        return Page(req).render(pageData)

    def __ordina__(req, action=None):
        from dao.Categoria import Categoria
        daos = Categoria().select(batchSize=None)
        pageData = {'file': "pg/addedit/ae_categoria_ordina",
                    "daos": daos,
                    }
        return Page(req).render(pageData)

    def __ordina_salva__(req, action=None):
        #print "VEDIAMO", req.form.to_dict()
        try:
            ordine = eval(req.form.get("ordine"))
        except:
            ordine = []
        from dao.Categoria import Categoria
        for a in ordine:
            d = Categoria().getRecord(id=a)
            d.ordine = ordine.index(a)
            d.persist()
        url_red = "/pg/ac_Categoria/"
        return Page(req).redirect(url_red)



    def __create__update__(req, action=None):
        """Aggiunge una riga alle pesate"""
        from dao.CategoriaTag import CategoriaTag
        id = req.form.get("id")
        if id != "None":
            d = Categoria().getRecord(id=int(id))
        else:
            d = Categoria()
        d.denominazione = str(req.form.get("denominazione"))
        d.denominazione_breve = str(req.form.get("denominazione_breve")[0:9])
        d.descrizione = str(req.form.get("descrizione"))
        d.icona_font = str(req.form.get("icona_font"))
        d.colore_icona_font = str(req.form.get("colore_icona_font"))
        a= Environment.session.query(func.max(Categoria.ordine)).all()
        if a:
            try:
                d.ordine = a[0][0] +1
            except:
                d.ordine = 0
        d.foto = bool(req.form.get("foto"))
        try:
            d.id_tipo_geo = int(req.form.get("id_tipo_geo"))
        except:
            d.id_tipo_geo = None
        try:
            d.id_licenza = int(req.form.get("id_licenza"))
        except:
            d.id_licenza = None
        try:
            d.id_tipo_categoria = int(req.form.get("id_tipo_categoria"))
        except:
            pass
        if "icona_categoria" in req.files:
            f = req.files["icona_categoria"]
            data = f.read()
            if data:
                d.icona_categoria = base64.b64encode(data)
        else:
            d.icona_categoria = ""
        d.persist()
        #tagsold = CategoriaTag().select(id_categoria=d.id, batchSize=None)
        #for t in tagsold:
            #t.delete()
        #for a in req.form.get("tagss").split(","):
            #if a:
                #tt = Tag().getRecord(id=a)
            #else:
                #tt = None
            #if not tt:
                #t =Tag()
                #t.name = a
                #t.persist()
            #ct = CategoriaTag()
            #ct.tag_name = a
            #ct.id_categoria = int(d.id)
            #ct.persist()
        url_red = "/pg/ac_Categoria/"
        return Page(req).redirect(url_red)

    def __delete__(req, action=None):
        """Cancella una riga"""
        from dao.Categoria import Categoria
        from dao.CategoriaTag import CategoriaTag
        id = int(req.form.get("id"))

        d = Categoria().getRecord(id=id)
        ff = CategoriaTag().select(id_categoria = id, batchSize=None)
        if ff:
            for f in ff:
                f.delete()
        try:
            d.delete()
            item = {"Result": "OK", }
        except:
            item = {
                "Result":"ERROR",
                "Message": "Cancellazione riga non riuscita"}
        jasoned = json.dumps(item, ensure_ascii=False, encoding='utf8')
        return Response(jasoned)

    def __get_tai__(req, action=None):
        tai = TipoCategoria().select(batchSize = None)
        item = {"Result":"OK",
                    "Options":[{"DisplayText":"","Value":""}]+ [{
                        "DisplayText":str(d.denominazione),
                        "Value":d.id} for d in tai]}
        jasoned = json.dumps(item, ensure_ascii=False, encoding='utf8')
        return Response(jasoned)

    def __get_tg__(req, action=None):
        tai = TipoGeo().select(batchSize = None)
        item = {"Result":"OK",
                    "Options":[{"DisplayText":"","Value":""}]+ [{
                        "DisplayText":str(d.denominazione),
                        "Value":d.id} for d in tai]}
        jasoned = json.dumps(item, ensure_ascii=False, encoding='utf8')
        return Response(jasoned)

    def __get_cate__(req, action=None):
        fk = req.args.get("fk")
        print "FKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK", fk
        tai = Categoria().select(batchSize = None)
        item = [{"id":d.id,"denominazione":str(d.denominazione)} for d in tai]
        jasoned = json.dumps(item, ensure_ascii=False, encoding='utf8')
        return Response(jasoned)

    def __preview__(req, action=None):
        id = int(req.form.get("id"))
        #salvaInSessione(req, chiave="id_fornitore_selezionato", valore=id)
        d = Categoria().getRecord(id=id)
        pageData = {'file': "/pg/categoria",
                    "dao": d}
        return Page(req).render(pageData)

    if leggiInSessione(req, sezione="Main", chiave="schema") is None:
        url_red = "/pg/main"
    elif action=="List":
        return __list__ (req, action=action)
    elif action=="show":
        return __show__(req, action=action)
    elif action=="Create" or action == "Update":
        return __create__update__(req, action=action)
    elif action=="Delete":
        return __delete__(req, action=action)
    elif action=="Ordina":
        return __ordina__(req, action=action)
    elif action=="OrdinaSalva":
        return __ordina_salva__(req, action=action)
    elif action == "GetTipoCategoria":
        return __get_tai__(req, action=action)
    elif action == "GetTipoGeo":
        return __get_tg__(req, action=action)
    elif action == "GetCate":
        return __get_cate__(req, action=action)
    elif action == "Preview":
        return __preview__(req, action=action)
    elif action == "Edit":
        return __edit__(req, action=action)
    else:
        return __show__(req, action=action)
